package com.cdy.store.repository;

import com.cdy.common.domain.FileEntity;
import com.cdy.common.domain.FileSectionEntity;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于内存的持久层实现
 * Created by 陈东一
 * 2019/10/19 0019 15:50
 */
public class FileRepositoryInMemory implements FileRepository {
    
    // fileMD5 -> file
    private static ConcurrentHashMap<String, FileEntity> fileDB = new ConcurrentHashMap<>();
    // fileId -> task
    private static ConcurrentHashMap<Long, List<FileSectionEntity>> fileTaskDB = new ConcurrentHashMap<>();
    
    @Override
    public FileEntity getFileByFileMd5(String md5) {
        return fileDB.get(md5);
    }

    @Override
    public FileEntity getFileById(Long id) {
        return fileDB.values().stream().filter(e->e.getId().equals(id)).findFirst().orElse(null);
    }

    @Override
    public synchronized List<FileSectionEntity> listTaskByFileId(Long fileId) {
        return fileTaskDB.get(fileId);
    }
    
    @Override
    public synchronized void insertFileSectionList(Long fileId, List<FileSectionEntity> list) {
        fileTaskDB.put(fileId, list);
    }
    
    @Override
    public void insertFile(FileEntity fileEntity) {
        fileDB.put(fileEntity.getMd5(), fileEntity);
    }
    
    @Override
    public FileSectionEntity getTaskByIdAndFileId(Long id, Long fileId) {
        List<FileSectionEntity> fileSectionEntities = fileTaskDB.get(fileId);
        if (fileSectionEntities == null) {
            return null;
        }
        for (FileSectionEntity fileSectionEntity : fileSectionEntities) {
            if (fileSectionEntity.getId().equals(id)) {
                return fileSectionEntity;
            }
        }
        return null;
    }

    @Override
    public FileSectionEntity getTaskById(Long id) {
        return fileTaskDB.values().stream().flatMap(Collection::stream)
                .filter(e -> e.getId().equals(id)).findFirst().orElse(null);
    }

    @Override
    public void updateTaskById(FileSectionEntity fileSectionEntity) {
        List<FileSectionEntity> fileSectionEntities = fileTaskDB.get(fileSectionEntity.getFileId());
        if (fileSectionEntities == null) {
            return;
        }
        for (int i = 0; i < fileSectionEntities.size(); i++) {
            FileSectionEntity sectionEntity = fileSectionEntities.get(i);
            if (sectionEntity.getId().equals(fileSectionEntity.getId())) {
                fileSectionEntities.set(i, fileSectionEntity);
                return;
            }
        }
    }

    @Override
    public void updateFileByMD5(FileEntity fileEntity) {
        fileDB.put(fileEntity.getMd5(), fileEntity);
    }
}
